package com.hongxun.budget.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.R;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.budget.utils.TestingUtils;
import com.hongxun.budget.utils.XUtils;
import com.hongxun.entity.LoginInfo;
import com.hongxun.net.UserNet;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.password)
    EditText password;

    @Override
    public  int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public  void initView(Bundle savedInstanceState) {
        username.setText((String) SPUtils.get(context, "username", ""));
        password.setText((String) SPUtils.get(context, "password", ""));
        if (LoginInfo.getInfo(context) != null) {
            startActivity(new Intent(context, MainActivity.class));
            finish();
        }
    }


    @OnClick(R.id.login)
    public void onViewClicked() {
        String name = getText(username);
        String pwd = getText(password);
        if (!TestingUtils.isEmpty(context, name, "用户名")) return;
        if (!TestingUtils.isEmpty(context, pwd, "密码")) return;
        UserNet.login(context, name, pwd, this);
    }

    @Override
    public void success(int i, JSONObject obj) {
        switch (i) {
            case 1:
                SPUtils.put(context, "token", obj.getString("token"));
                LoginInfo loginInfo = JSON.parseObject(obj.getString("user"), LoginInfo.class);
                LoginInfo.save(context, loginInfo);
                UserNet.data(this, this);
                break;
            case 20:
                XUtils.setBaseData(context, obj, this);
                break;
            case 30:
                XUtils.setBaseData2(context, obj, this);
                break;
            case 40:
                XUtils.setBaseData3(context, obj, this);
                break;
            case 3:
                UserNet.data2(this, this);
                break;
            case 4:
                UserNet.data3(this, this);
                break;
            case 5:
                T.showLong(context, "缓存成功");
                finish();
                startActivity(new Intent(context, MainActivity.class));
                break;
        }
    }
}